const Koa = require('koa')
const http = require('http')
const https = require('https')
const R = require('ramda')
const database = require('./database/index')
const fs = require('fs')
const path = require('path')

const middleWares = ['transmit', 'general', 'router', 'history']

const app = new Koa()
const useMiddlewares = (app) => {
  R.map(
    R.compose(
      R.forEachObjIndexed(e => e(app)),
      require,
      str => `./middleware/${str}.js`
    )
  )(middleWares)
}

const server = http.createServer(app.callback())

const options = {
  key: fs.readFileSync(path.resolve(__dirname, '../keys/server.key')),
  cert: fs.readFileSync(path.resolve(__dirname, '../keys/server.crt'))
}
const serverSSL = https.createServer(options, app.callback())

require('./websocket')(server)

const port = 8082
server.listen(port, () => {
  console.log(`server in running at port ${port}`)
})
/*serverSSL.listen(443, () => {
  console.log(`https server is running`)
})*/

;(async () => {
  await database()
  useMiddlewares(app)
})()
